package com.chl.legou.seckill.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chl.legou.common.utils.DateUtils;
import com.chl.legou.common.utils.SystemConstants;
import com.chl.legou.seckill.dao.SeckillGoodsDao;
import com.chl.legou.seckill.po.SeckillGoods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author chlong
 * @date 2022/5/23
 */
//@Component
@Slf4j
public class SeckillGoodsPushTask {
    @Autowired
    private SeckillGoodsDao seckillGoodsDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 每30秒执行一次
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void loadGoodsPushRedis(){
        //1.获取当前的时间对应的5个时间段
        List<Date> dateMenus = DateUtils.getDateMenus();
        //2.循环遍历5个时间段，获取对应时间
        for (Date startTime : dateMenus) {
            String extName = DateUtils.data2str(startTime, DateUtils.PATTERN_YYYYMMDDHH);
            //3.将循环到的时间段 作为条件 从数据库中执⾏查询 得出数据集
            /**
             * select * from seckill_goods_ where
                 stock_count>0
                 and `status`='1'
                 and start_time > 开始时间段
                 and end_time < 开始时间段+2hour and id not in (redis中已有的id)
             */
            QueryWrapper<SeckillGoods> query = Wrappers.<SeckillGoods>query();
            query.eq("status_","1");
            query.gt("stock_count_",0);
            query.ge("start_time_",startTime);
            query.lt("end_time_",DateUtils.addDateHour(startTime,2));

            //排除掉redis已有商品
            Set keys = redisTemplate.boundHashOps(SystemConstants.SEC_KILL_GOODS_PREFIX + extName).keys();
            if (keys != null && keys.size() > 0){
                query.notIn("id_",keys);
            }
            List<SeckillGoods> seckillGoods = seckillGoodsDao.selectList(query);

            //4.将数据集存储到redis中(key field value的数据格式 )
            /**
             * key(时间段:2019090516)
             * field (id:1) value(商品的数据pojo)
             * field (id:2) value(商品的数据pojo)
             *key(时间段:2019090518)
             * field (id:3) value(商品的数据pojo)
             * field (id:4) value(商品的数据pojo)
             */
            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps(SystemConstants.SEC_KILL_GOODS_PREFIX + extName).put(seckillGood.getId(),seckillGood);
                //设置有效期
                // redisTemplate.expireAt(SystemConstants.SEC_KILL_GOODS_PREFIX + extName, DateUtil.addDateHour(starttime, 2));
            }
        }
    }
}
